package cn.edu.bupt.blog.web;

import cn.edu.bupt.blog.NotFoundException;
import cn.edu.bupt.blog.service.BlogService;
import cn.edu.bupt.blog.service.TagService;
import cn.edu.bupt.blog.service.TypeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.web.PageableDefault;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;

@Controller
public class IndexController {

    @Autowired
    private BlogService blogService;

    @Autowired
    private TypeService typeService;

    @Autowired
    private TagService tagService;
    @GetMapping
    public String index(@PageableDefault(size = 3,sort = {"updateTime"},direction = Sort.Direction.DESC) Pageable pageable,
                        Model model) {
        model.addAttribute("page",blogService.listBlog(pageable));
        model.addAttribute("types",typeService.listTop(6));
        model.addAttribute("tags",tagService.listTag(10));
        model.addAttribute("recommenBlogs",blogService.listRecommendBlog(8));
        return "index";
    }

    @PostMapping("/search")
    public String search (@PageableDefault(size = 3,sort = {"updateTime"},direction = Sort.Direction.DESC) Pageable pageable,
                          @RequestParam String query,Model model) {
        model.addAttribute("page",blogService.listBlog(query,pageable));
        model.addAttribute("query",query);
        return "search";
    }

    @GetMapping("/blog")
    public String blog (@RequestParam Long id,Model model) {
        model.addAttribute("blog",blogService.getAndConvert(id));
        return "blog";
    }

    @GetMapping("/footer/newBlogList")
    public String newBlogList(Model model) {
        model.addAttribute("blogList",blogService.listRecommendBlog(3));
        return "_fragments :: newBlogList";
    }
}
